package com.jzlin.funhub.framework.core.exception;

import cn.dev33.satoken.exception.NotLoginException;
import com.jzlin.funhub.framework.core.http.RestRet;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLException;

/**
 * 全局异常处理器.
 *
 * @author linjz
 * @since 2025/7/26
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    // 处理所有未捕获的异常
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseEntity<RestRet> handleException(Exception e) {
        log.error(e.getMessage(), e);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(RestRet.createFailureRet(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage()));
    }

    // 未登录异常
    @ExceptionHandler(NotLoginException.class)
    @ResponseBody
    public ResponseEntity<RestRet> handleException(NotLoginException e) {
        log.error(e.getMessage(), e);
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                .body(RestRet.createFailureRet(HttpStatus.UNAUTHORIZED.value(), e.getMessage()));
    }


    // 数据库异常
    @ExceptionHandler(SQLException.class)
    @ResponseBody
    public ResponseEntity<RestRet> handleException(SQLException e) {
        log.error(e.getMessage(), e);
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                .body(RestRet.createFailureRet(HttpStatus.UNAUTHORIZED.value()));
    }
}
